<template>
    <div id="p-searchbox-wrapper">
        <div class="p-searchbox-container">
            <div class="tags-container">
                <!-- 已选tags -->
                <div class="tags-list" ref="tagsList">
                    <div class="tags-item" v-for="(search,index) of content" :key="search.id">
                        <span class="tags-item__key">
                            {{ options.find(item => item.id === search.id).label }}
                        </span>
                        <span>: &nbsp;</span>
                        <span class="tags-item__value">
                            {{ search.value }}
                        </span>
                        <!-- 删除tag -->
                        <div class="tags-item__del" @click="deleteTag(index)">
                            <i class="el-icon-close"></i>
                        </div>
                    </div>
                </div>
                <!-- 在选tags -->
                <div class="search-filed">
                    <!-- 根据type -->
                    <span class="search-filed__prop">{{ selectedProp.label || '' }}</span>
                    <span>{{ selectedProp.label ? ':' : '' }}</span>
                    <span class="search-filed__input">
                        <input
                            v-model="selectedValue"
                            v-popover:popover
                            ref="searchInput"
                            @click="onSearchClick"
                            @blur="onSearchBlur"
                            @focus="onSearchFocus"
                            @keyup.enter="onSearchConfirm"
                            @keyup.delete="onSearchDelete"
                            :placeholder="acPlaceholder"
                            clearable
                        />
                    </span>
                </div>
                <!-- 右侧icon按钮 -->
                <div class="search-right-icons">
                    <div class="right-icons__del" @click="deleteIptCotent" v-if="!isHideDeleteIcon"> 
                        <i class="el-icon-close"></i>
                    </div>
                    <div class="right-icons__search" v-if="isHideSerachIcon">
                        <img src="../../assets/images/search.svg">
                    </div>
                </div>
            </div>
        </div>
        <div class="p-searchbox-popovers" :style="{ left: popoverLeft, }">
            <!-- prop 选择，popper-class用于样式覆盖 -->
            <div v-if="isSelectedProp">
                <el-popover
                    popper-class="popover-prop-wrap"
                    :value="showPropPanel"
                    ref="popover"
                    placement="bottom-start"
                    trigger="manual"
                    :popper-options="popperOptions"
                >
                    <div class="popover-prop__list">
                        <p
                            class="popover-prop__list-item"
                            v-for="item of options"
                            :key="item.id"
                            @click="onSelectedProp(item)"
                        >
                            {{ item.label }}
                        </p>
                    </div>
                </el-popover>
            </div>
            <!-- value 选择 -->
            <!-- 单选 -->
            <div v-if="currentType === 'radio' && !isSelectedProp">
                <el-popover
                    popper-class="popover-prop-wrap"
                    :value="showValuePanel"
                    ref="popover"
                    placement="bottom-start"
                    trigger="manual"
                >
                    <div class="popover-prop__list">
                        <p
                            class="popover-prop__list-item"
                            v-for="(item, index) in filterValueOptions"
                            :key="index"
                            @click="onSelectedValue(item)"
                        >
                            {{ item.label }}
                        </p>
                    </div>
                </el-popover>
            </div>
            <!-- input 输入 -->
            <div v-if="currentType === 'input' && !isSelectedProp"></div>

            <!-- 时间范围 -->
            <div v-if="currentType === 'dateRange' && !isSelectedProp">
                <el-popover
                    popper-class="popover-prop-wrap-date"
                    :value="showValuePanel"
                    ref="popover"
                    placement="bottom-start"
                    trigger="manual"
                >
                    <span>
                        <p class="searchDescription">请选择日期时间</p>
                        <el-form :model="timeForm" label-width="70px">
                            <el-form-item label="开始时间">
                                <el-date-picker
                                    value-format="yyyy/MM/dd hh:mm:ss"
                                    v-model="timeForm.startTime"
                                    type="datetime"
                                    placeholder="选择日期时间">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="结束时间">
                                <el-date-picker
                                    value-format="yyyy/MM/dd hh:mm:ss"
                                    v-model="timeForm.endTime"
                                    type="datetime"
                                    placeholder="选择日期时间">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item>
                                <el-button @click="dataTimeConfirm">确定</el-button>
                                <el-button @click="dataTimeCancel">取消</el-button>
                            </el-form-item>
                        </el-form>
                    </span>
                </el-popover>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 默认筛选id。把 defaultPropId 作为 props 属性，在没有传入该 prop 时，在mouted默认选取 options 的第一个 id 作为默认值
            defaultPropId: 'name',
            acPlaceholder: '输入关键字搜索',
            // 当变化时，通过emit广播出去,id 相同，则覆盖
            content: [],
            selectedPropId: '', // 选中的 prop id
            selectedValue: '', // input 值
            showPropPanel: false,
            showValuePanel: false,
            popperOptions: {
                boundariesElement: 'viewport',
            },
            isHideDeleteIcon: true,
            isHideSerachIcon: true,
            timeForm: {
                startTime: '',
                endTime: '',
            },
            finalTime: '',
            popoverLeft: 0
        }
    },
    mounted() {},
    methods: {
        // search input methods
        deleteTag(index) {
            this.content.splice(index,1)
            if(this.content.length > 0) {
                this.isHideDeleteIcon = false;
                this.isHideSerachIcon = false;
            } else {
                this.isHideDeleteIcon = true;
                this.isHideSerachIcon = true;
            }
            this.$emit('change', this.content)
        },
        deleteIptCotent() {
            this.content = null;
            this.content = []
            this.selectedPropId = '';
            this.selectedValue = '';
            this.isHideDeleteIcon = true;
            this.isHideSerachIcon = true;
            this.$emit('change', this.content)
        },
        dataTimeConfirm() {
            if (this.timeForm.startTime === '') {
                this.$message.error('请选择开始时间');
                return 
            } else if (this.timeForm.endTime === '') {
                this.$message.error('请选择结束时间');
                return 
            }
            this.finalTime = this.timeForm.startTime + '-' + this.timeForm.endTime
            this.handleSearch(this.finalTime);
        },
        dataTimeCancel() {
            this.timeForm.startTime = '';
            this.timeForm.endTime = '';
            this.selectedPropId = ''
        },
        onSearchBlur() {
            if (this.selectedPropId === '') {
                this.isHideDeleteIcon = true;
                this.isHideSerachIcon = true;
            } else if (this.selectedPropId !== '') {
                this.isHideDeleteIcon = false;
                this.isHideSerachIcon = false;
            }
            if (this.currentType === 'dateRange') return false;
            this.closePopover();
        },
        onSearchClick() {
            this.openPopover();
            this.popoverLeft = this.$refs.tagsList.offsetWidth;
        },
        onSearchFocus() {
            this.openPopover();
            if (this.content.length >= 0) {
                this.isHideDeleteIcon = false;
                this.isHideSerachIcon = false;
            } else {
                this.isHideDeleteIcon = true;
                this.isHideSerachIcon = true;
            }
        },
        onSearchConfirm(e) {
            e.preventDefault();
            this.$refs.searchInput.blur();
            const content = this.selectedValue;
            if (!content) return false;
            this.handleSearch(content);
        },
        onSearchDelete() {
            if (this.selectedPropId && !this.selectedValue) {
                this.selectedPropId = '';
                this.$refs.searchInput.blur();
            } else {
                if (this.content.length > 0) {
                    this.content.splice(this.content.length - 1, 1);
                }
            }
        },
        handleSearch(content) {
            const propId = this.selectedPropId || this.defaultPropId;
            // 判断是否有相同的 id，有则替换content
            const index = this.content.findIndex(item => item.id === propId);
            if (index > -1) {
                this.content[index].value = content;
            } else {
                this.content.push({
                    id: this.selectedPropId,
                    value: content,
                });
            }

            this.resetSearchFiled();
            this.$nextTick(() => {
                this.$refs.popover.updatePopper();
            });
            this.$emit('change', this.content);
        },
        // 重置 search filed
        resetSearchFiled() {
            this.selectedPropId = '';
            this.selectedValue = '';
        },
        // 关闭popover
        closePopover() {
            this.showPropPanel = false;
            this.showValuePanel = false;
        },
        // 打开 popover
        openPopover() {
            if (this.isSelectedProp && !this.showPropPanel) {
                this.showPropPanel = true;
            }

            if (!this.isSelectedProp && !this.showValuePanel) {
                this.showValuePanel = true;
            }

            this.rerenderPopover();
        },
        rerenderPopover() {
            if (this.$refs.popover) {
                this.$nextTick(() => {
                    this.$refs.popover.updatePopper();
                });
            }
        },
        // select prop methods
        onSelectedProp(item) {
            this.selectedPropId = item.id;
        },
        onSelectedValue(item) {
            this.closePopover();
            this.handleSearch(item.label);
        },
    },
    props: {
        options: {
            type: Array,
            required: true,
        },
    },
    computed: {
        // 当前选中的 options[x]
        selectedProp: function () {
            return this.options.find(item => item.id === this.selectedPropId) || {};
        },
        // 当前选中 prop 对应的 type 功能类型
        currentType: function () {
            return this.selectedProp.type;
        },
        // 标识当前选择prop还是value
        isSelectedProp: function () {
            return !this.selectedPropId;
        },
        filterValueOptions: function () {
            const options = this.selectedProp.options || [];
            const filterOption = options.filter(item => {
                    return (item.label.toLowerCase().indexOf(this.selectedValue.toLowerCase())=== 0) 
            })
            return filterOption
        },
    },
    watch: {
        selectedPropId: function (newVal) {
            // 如果 prop 已选择，对 autocomplete 做相应的处理
            if (newVal) {
                this.acPlaceholder = '';
            } else {
                this.acPlaceholder = '默认按照名称搜索';
            }
        },
    },
};
</script>

<style lang="less" scoped>
#p-searchbox-wrapper {
    * {
        box-sizing: border-box;
    }

    p {
        margin: 0;
    }

    z-index: 999;
    span {
        font-size: 14px;
    }
    width: 480px;
    height: 30px;
    border: 1px solid #DFE1E6;
    border-radius: 4px;

    .p-searchbox-container {
        height: 100%;
        padding: 4px;
        display: flex;
        align-items: center;
        .tags-container {
            height: 29px;
            display: flex;
            flex: 1;
            .tags-list {
                display: inline-flex;
                .tags-item {
                    display: flex;
                    flex-direction: row;
                    align-items: center;
                    background-color: #dfe1e6;
                    padding: 4px;
                    margin-right: 10px;
                    .tags-item__del {
                        margin-top: 3px;
                    }
                }
            }
            .search-filed {
                flex: 1;
                display: flex;
                align-items: center;
                .search-filed__input {
                    flex: 1;
                    padding-left: 6px;
                    /deep/ .el-input .el-input__inner {
                        padding: 0 !important;
                    }
                    /deep/ input {
                        font-family: PingFangSC-Regular;
                        font-size: 12px;
                        color: #575D6C;
                        width: 100%;
                        height: 100%;
                        border: none;
                        outline: medium;
                    }
                    /deep/ input::-moz-placeholder { 
                        color: #a1a1a1; 
                    }
                }
            }
            .search-right-icons {
                display: flex;
                margin-top: 6px;
                .right-icons__del {
                    margin-right: 8px;
                }
                .right-icons__search {
                    margin-right: 8px;
                }
            }
        }
    }
}
</style>
<style lang="less">
.searchDescription {
    margin: 0 0 10px 0;
    color: #979797;
}
.el-popover.popover-prop-wrap {
    min-width: 0 !important;
    padding: 10px 0 !important;
    font-size: 12px;
    .popover-prop__list {
        display: flex;
        flex-direction: column;
        .popover-prop__list-item {
            height: 30px;
            line-height: 30px;
            margin: 0 !important;
            padding: 0 20px;
            text-align: center;
            cursor: pointer;
            &:hover {
                background-color: #f5f7fa;
            }
        }
    }
}
.popover-prop-wrap-date {
    padding-bottom: 0;
    .searchDescription {
        font-size: 12px;      
    }
    .el-form-item {
        margin-bottom: 18px;
        .el-button {
            padding: 8px 20px;
            &:hover {
                border-color: #0a4cee;
                background-color: #0a4cee;
                color: #fff;
            }
        }
    }
    .el-date-editor.el-input {
        width: 200px;
    }
}
</style>
